package com.oocl.scan.dao.impl;

import com.arangodb.ArangoCursor;
import com.arangodb.entity.BaseDocument;
import com.arangodb.util.MapBuilder;
import com.oocl.scan.dao.BasicDao;
import com.oocl.scan.dao.ComponentDao;
import com.oocl.scan.model.Component;
import java.util.Map;

public class ComponentDaoImpl extends BasicDao implements ComponentDao {

  private static final String COMPONENTS = "components";

  @Override
  public Component findByNameAndModule(String name, String module) {
    String query = "FOR t IN "+ COMPONENTS +" FILTER t.name == @name FILTER t.module == @module RETURN t";
    Map<String, Object> bindVars = new MapBuilder().put("name", name).put("module", module).get();
    ArangoCursor<Component> cursor = getDataBase().query(query, bindVars, null, Component.class);
    Component object = null;
    while (cursor.hasNext()){
      object = cursor.next();
      break;
    }
    return object;
  }

  @Override
  public void add(Component component) {
    BaseDocument document = new BaseDocument();
    document.addAttribute("name", component.getName());
    document.addAttribute("module", component.getModule());
    document.addAttribute("type", component.getType());
    document.addAttribute("domain", component.getDomain());
    document.addAttribute("type",component.getType());
    getDataBase().collection(COMPONENTS).insertDocument(document);
  }

  @Override
  public void delete(Component component) {
    Component result = findByNameAndModule(component.getName(),component.getModule());
    if(result != null){
      String query = "FOR t IN "+ COMPONENTS +" FILTER t.name == @name FILTER t.module == @module "
          + "REMOVE t IN " + COMPONENTS + " LET removed = OLD RETURN removed";
      Map<String, Object> bindVars = new MapBuilder().put("name", component.getName()).put("module", component.getModule()).get();
      getDataBase().query(query, bindVars, null, Component.class);
    }
  }

  @Override
  public Component findByName(String name) {
    String query = "FOR t IN "+ COMPONENTS +" FILTER t.name == @name RETURN t";
    Map<String, Object> bindVars = new MapBuilder().put("name", name).get();
    ArangoCursor<Component> cursor = getDataBase().query(query, bindVars, null, Component.class);
    Component object = null;
    while (cursor.hasNext()){
      object = cursor.next();
      break;
    }
    return object;
  }
}
